package com.talos.ums.service.roleuser;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.roleuser.vo.UmsRoleUserPageReqVO;
import com.talos.ums.controller.admin.roleuser.vo.UmsRoleUserSaveReqVO;
import com.talos.ums.dal.dataobject.roleuser.UmsRoleUserDO;
import com.talos.ums.dal.mysql.roleuser.UmsRoleUserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 角色用户关系表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsRoleUserServiceImpl implements UmsRoleUserService {

    @Resource
    private UmsRoleUserMapper roleUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createRoleUser(UmsRoleUserSaveReqVO createReqVO) {
        // 插入
        UmsRoleUserDO roleUser = BeanUtils.toBean(createReqVO, UmsRoleUserDO.class);
        roleUserMapper.insert(roleUser);
        // 返回
        return roleUser.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRoleUser(UmsRoleUserSaveReqVO updateReqVO) {
        // 校验存在
        validateRoleUserExists(updateReqVO.getId());
        // 更新
        UmsRoleUserDO updateObj = BeanUtils.toBean(updateReqVO, UmsRoleUserDO.class);
        roleUserMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoleUser(Long id) {
        // 校验存在
        validateRoleUserExists(id);
        // 删除
        roleUserMapper.deleteById(id);
    }

    private void validateRoleUserExists(Long id) {
        if (roleUserMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsRoleUserDO getRoleUser(Long id) {
        return roleUserMapper.selectById(id);
    }

    @Override
    public PageResult<UmsRoleUserDO> getRoleUserPage(UmsRoleUserPageReqVO pageReqVO) {
        return roleUserMapper.selectPage(pageReqVO);
    }

}
